package com.chen.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chen.config.AliPayConfig;
import com.chen.entity.User;
import com.chen.entity.UserRechargeOrders;
import com.chen.service.UserPayService;
import com.chen.service.UserRechargeOrdersService;
import com.chen.utils.RedisWorker;
import com.chen.utils.UserThreadLocal;
import com.chen.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author cws
 * @since
 */
@Service
@Slf4j
public class UserPayServiceImpl implements UserPayService {

    @Resource
    private UserRechargeOrdersService userRechargeOrdersService;

    @Resource
    private RedisWorker redisWorker;

    @Resource
    AliPayConfig aliPayConfig;


    @Override
    public Result recharge(Long amount, Long orderId, HttpServletResponse httpResponse,String token) {
        if (amount == null) {
            throw new RuntimeException("金额不能为空");
        }
        User user = UserThreadLocal.get();
        UserRechargeOrders userRecharge =new UserRechargeOrders();
        if (orderId != null) {
            userRecharge = userRechargeOrdersService.getById(orderId);
        } else {
//            创建订单
            userRecharge.setUserId(user.getId());
            userRecharge.setAmount(BigDecimal.valueOf(amount));
            userRecharge.setStatus("待支付");
            long number = redisWorker.nextId("recharge:" + user.getId() + ":");
            userRecharge.setOrderNumber("REC" + number);
            userRecharge.setPaymentMethod("支付宝");
            userRecharge.setCancelledAt(LocalDateTime.now());
            userRechargeOrdersService.save(userRecharge);
        }
        if (userRecharge==null){
            throw new RuntimeException("订单不存在");
        }

        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), aliPayConfig.getFormat(), aliPayConfig.getCharset(),
                aliPayConfig.getAlipayPublicKey(), aliPayConfig.getSignType());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        log.info("=========支付宝统一收单交易创建接口========{}", aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", userRecharge.getOrderNumber());
        bizContent.put("total_amount", userRecharge.getAmount());
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderSn", userRecharge.getOrderNumber());
        map.put("type", "user");
        bizContent.put("subject", JSONUtil.toJsonStr(map));
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(form);
    }
}

